<?php

namespace app\admin\model;

use app\admin\validate\BlogValidate;
use think\Model;
use think\Request;

class Blog extends Model
{
    /**
     * blogselect查询数据
     * blogsearch搜索数据
     * blogcreate添加数据
     * blogchaxun查询通过ID主键查到的数据
     * blogupdate修改数据
     * blogdelete删除数据
     */
    public function blogselect(){
        return Blog::alias(['tp_cate'=>'c','tp_blog'=>'b'])
            ->field('b.*,c.title')
            ->join('tp_cate','c.id=b.cid')
            ->paginate();
    }
    public function blogsearch($data)
    {
        $id = $data['id'];
        $name = $data['name'];
        if(empty($id) && !empty($name)){
            return Blog::alias(['tp_blog' => 'b', 'tp_cate' => 'c'])
                ->field('b.*,c.title')
                ->join('tp_cate', 'c.id=b.cid')
                ->where('name', 'like', "%$name%")
                ->select();
        }else if(!empty($id) && empty($name)){
            return Blog::alias(['tp_blog' => 'b', 'tp_cate' => 'c'])
                ->field('b.*,c.title')
                ->join('tp_cate', 'c.id=b.cid')
                ->where('cid', $id)
                ->select();
        }else if(empty($id) && empty($name)){
            return Blog::alias(['tp_blog' => 'b', 'tp_cate' => 'c'])
                ->field('b.*,c.title')
                ->join('tp_cate', 'c.id=b.cid')
                ->select();
        }else{
            return Blog::alias(['tp_blog' => 'b', 'tp_cate' => 'c'])
                ->field('b.*,c.title')
                ->join('tp_cate', 'c.id=b.cid')
                ->where('cid', $id)
                ->where('name', 'like', "%$name%")
                ->select();
        }

    }
    public function blogcreate($data){
        $validate =new BlogValidate();
        if(!$validate->check($data)){
            return $validate->getError();
        }
        $shuju =Blog::create($data);
        if($shuju) {
            return 1;
        }
    }
    public function blogchaxun($id){
        return Blog::where('id',$id)->find();
    }
    public function blogupdate($id,$data){
        $validate =new BlogValidate();
        if(!$validate->check($data)){
            return $validate->getError();
        }
        $shuju =Blog::where('id',$id)->update($data);
        if($shuju){
            return 1;
        }else{
            return '修改失败';
        }
    }
    public function blogdelete($id){
        return Blog::destroy($id);
    }
}
